define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "static/app/hddc/hddccjcommon/hddccjCommon",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock, HddccjCommon) {

    var sysPath = getServer() + "/static/app/hddc/hddcStation";

    var hddcStationFormHtml = sysPath + "/views/hddcStationForm.html";
    var getHddcStationController = function () {
        return getServer() + "/hddc/hddcStation";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initcreateProvince();
        HddccjCommon.initProjectSelect("projectNameCondition"); //初始化查询的项目名称
        createHddcStationGrid();
    };
    var initDatetimePicker = function () {
        $("#testtime").datetimepicker({
            //设置使用语言：cn是自定义的中文版本，还可以扩展其他语言版本
            language: "cn",
            //输出格式化
            format: 'yyyy-mm-dd',
            //直接选择‘今天’
            todayBtn: true,
            //设置最精确的时间选择视图
            minView: 'month',
            //高亮当天日期
            todayHighlight: true,
            //选择完毕后自动关闭
            autoclose: true
        });

        $("#starttime").datetimepicker({
            //设置使用语言：cn是自定义的中文版本，还可以扩展其他语言版本
            language: "cn",
            //输出格式化
            format: 'yyyy-mm-dd hh:ii:ss',
            //直接选择‘今天’
            todayBtn: true,
            //设置最精确的时间选择视图
            // minView: 'month',
            startView: "hour",
            minuteStep: 3,
            //高亮当天日期
            todayHighlight: true,
            //选择完毕后自动关闭
            autoclose: true
        });
    }
    var initcreateProvince = function () {
        var html = "";
        $("#cityCodeSelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#cityCodeSelect option").remove();
            $("#cityCodeSelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#cityCodeSelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#cityCodeSelect").append(html);
                }
            });
        });
        $("#cityCodeSelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    }

    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            createHddcStationGrid();
        });
        $("#btnReset").click(function () {
            $("#provinceSelect").val("");
            $("#cityCodeSelect").val("");
            $("#areaSelect").val("");
            $("#projectNameCondition").val("");
            $("#stationnameCondition").val("");
        });
    };
    //导入
    var importForm = function () {

        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getServer() + "/excel/地震台站-点.xls";
            $("#downloadZwExcelTemplate").attr("href", url);
        });

        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file", uploadinput.files[0]);
            $.ajax({
                url: getHddcStationController() + "/importDisaster",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    Util.alert(data);
                    createHddcStationGrid();
                }
            });
        });
    };
    //导出
    var exportForm = function () {
        var province = $("#provinceSelect").val();
        var cityCode = $("#cityCodeSelect").val();
        var area = $("#areaSelect").val();
        var projectName = $("#projectNameCondition").val();
        var stationname = $("#stationnameCondition").val();
        window.location.href = getHddcStationController() + "/exportFile?province=" + province + "&cityCode=" + cityCode + "&area=" + area + "&projectName=" + projectName + "&stationname=" + stationname;
    };
    var createHddcStationGrid = function () {
        $("#hddcStationGrid").datagrid({
            url: getHddcStationController() + "/queryHddcStations",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
                {field: "ck", checkbox: true},
                {
                    field: 'id', sortable: true,
                    title: '台站编码',
                    width: '20%',
                    align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        return '<a href="#" onclick="_editHddcStation(\'' + rowData.uuid + '\');"> ' + rowData.id + ' </a> '
                    }
                },
                {
                    field: 'stationname',
                    title: '台站名称',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'province', sortable: true,
                    title: '省',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'cityCode', sortable: true,
                    title: '市(编码需要)',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'area', sortable: true,
                    title: '区（县）',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'projectName',
                    title: '项目名称',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'taskName',
                    title: '任务名称',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'city', sortable: true,
                    title: '所在城市',
                    width: '20%',
                    align: 'center',
                },
                {
                    field: 'createUserName',
                    title: '上传人',
                    width: '20%',
                    align: 'center'
                },
                {
                    field: 'updateTime',
                    title: '上传时间',
                    width: '20%',
                    align: 'center',
                },
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text: "添加",
                handler: function () {
                    addHddcStation();
                }
            }, {
                iconCls: 'fa fa-trash-o',
                text: "删除",
                handler: function () {
                    deleteHddcStation();
                }
            }, {
                iconCls: 'fa fa-upload',
                text: "导入",
                handler: function () {
                    importForm();
                }
            }, {
                iconCls: 'fa fa-download',
                text: "导出",
                handler: function () {
                    exportForm();
                }
            }],
            queryParams: {
                province: $("#provinceSelect").val(),
                cityCode: $("#cityCodeSelect").val(),
                area: $("#areaSelect").val(),
                projectName: $("#projectNameCondition").val(),
                stationname: $("#stationnameCondition").val(),
            },
            pagination: true,
            pageSize: 10
        });
    };
    var formValidator = function () {
        $("#hddcStationForm").validate({
            rules: {
                province: {
                    required: true,
                },
                cityCode: {
                    required: true,
                },
                area: {
                    required: true,
                },
                id: {
                    required: true,
                    rangelength: [17, 17]
                },
                projectName: {
                    required: true,
                },
                taskName: {
                    required: true,
                },
                stationtype: {
                    required: true,
                },
                instrument: {
                    required: true,
                },
                stationlongitude: {
                    range: [-180, 180],
                    number: true,
                },
                stationlatitude: {
                    range: [-90, 90],
                    number: true,
                },
                elevation: {
                    maxlength: 8,
                    number: true,
                },
                sensitivityns: {
                    maxlength: 4,
                    digits: true,
                },
                sensitivityew: {
                    maxlength: 4,
                    digits: true,
                },
                sensitivityv: {
                    maxlength: 4,
                    digits: true,
                },
                extends4: {
                    required: true,
                },
            },
            messages: {
                province: {
                    required: "省不允许为空!",
                },
                cityCode: {
                    required: "市(编码需要)不允许为空!",
                },
                area: {
                    required: "区（县）不允许为空!",
                },
                id: {
                    required: "台站编码不允许为空!",
                    rangelength: "长度为17位!"
                },
                projectName: {
                    required: "项目名称不允许为空!",
                },
                taskName: {
                    required: "任务名称不允许为空!",
                },
                stationtype: {
                    required: "台站类型不允许为空!",
                },
                instrument: {
                    required: "仪器类型不允许为空!",
                },
                stationlongitude: {
                    required: "台站经度不允许为空!",
                },
                stationlatitude: {
                    required: "台站纬度不允许为空!",
                },
                elevation: {
                    required: "台站海拔高度[米]要不为空的长度不大于8的浮点数!",
                },
                sensitivityns: {
                    required: "仪器南北响应灵敏度 [count*s/μm]要长度不大于4的整数!",
                },
                sensitivityew: {
                    required: "仪器东西响应灵敏度 [count*s/μm]要长度不大于4的整数!",
                },
                sensitivityv: {
                    required: "仪器垂直响应灵敏度 [count*s/μm]要长度不大于4的整数!",
                },
            }
        });
    };
    var getHddcStation = function (id) {
        $.ajax({
            url: getHddcStationController() + "/" + id,
            type: "get",
            success: function (data) {
                editProvince(data.province, data.cityCode, data.area);
                // 回显项目名称
                // $("#projectName").val(data.projectName);
                // 回显任务名称
                HddccjCommon.initEditTaskSelect("taskName", data.projectName);
                // $("#taskName").val(data.taskName);
                HddccjCommon.viewFileUpload(data.extends8);
                Tool.deserialize("hddcStationForm", data);
            }
        });
    };
    var initcreateProvinceForm = function () {
        var html = "";
        $("#cityCode").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#cityCode option").remove();
            $("#cityCode").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#cityCode").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#cityCode").append(html);
                }
            });
        });
        $("#cityCode").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }
    var addHddcStation = function () {
        var slidebar = Util.slidebar({
            url: hddcStationFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                initcreateProvinceForm();
                formValidator();
                initDatetimePicker();
                HddccjCommon.initProjectSelect("projectName"); //添加页面项目名称下拉
                HddccjCommon.initTaskSelect("projectName", "taskName"); //添加页面任务名称根据项目名称切换
                HddccjCommon.tipsInfo();
                HddccjCommon.fileUpload();
                $("#saveBtn").on("click", function () {
                    if ($("#hddcStationForm").valid()) {
                        var data = Tool.serialize("hddcStationForm");
                        data.projectId = $("#projectName").val();
                        data.taskId = $("#taskName").val();
                        $.ajax({
                            url: getHddcStationController() + "/save",
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createHddcStationGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    var editProvince = function (Province, CityCode, Area) {

        var html = "";
        $("#cityCode").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {

                        var divisionId = item.divisionId;
                        var htmlCityCode = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#cityCode").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#cityCode').val(CityCode);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#area").append(htmlArea);
                                    $('#area').val(Area);
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {

                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == CityCode) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#area").append(htmlArea);
                                                    $('#area').val(Area);
                                                }
                                            });
                                        }
                                        htmlCityCode += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#cityCode").append(htmlCityCode);
                                    $('#cityCode').val(CityCode);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
                $('#province').val(Province);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#cityCode option").remove();
            $("#cityCode").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#cityCode").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#cityCode").append(html);
                }
            });
        });
        $("#cityCode").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }
    window._editHddcStation = function (hddcStationId) {
        var slidebar = Util.slidebar({
            url: hddcStationFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                formValidator();
                initDatetimePicker();
                HddccjCommon.initProjectSelect("projectName"); //编辑页面项目名称下拉
                HddccjCommon.initTaskSelect("projectName", "taskName"); //编辑页面任务名称根据项目名称切换
                HddccjCommon.tipsInfo();
                getHddcStation(hddcStationId);
                $("#saveBtn").on("click", function () {
                    if ($("#hddcStationForm").valid()) {
                        var data = Tool.serialize("hddcStationForm");
                        data.projectId = $("#projectName").val();
                        data.taskId = $("#taskName").val();
                        data.qualityinspectionStatus = "0"; // 修改数据，质检状态变为未质检
                        $.ajax({
                            url: getHddcStationController() + "/update",
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createHddcStationGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    var deleteHddcStation = function () {
        var rows = $("#hddcStationGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的数据?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.uuid + ",";

            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getHddcStationController() + "/delete",
                contentType: "application/json",
                data: ids,
                type: "post",
                success: function (data) {
                    createHddcStationGrid();
                }
            });
        }, function () {
            return;
        });

    };

    return {
        init: init
    };
});
